import React, { useRef, useState, useEffect, useCallback } from 'react';
import './ImageViewer.css';

const TDCImageViewer = ({ 
  data, 
  type, 
  viewId, 
  currentTool, 
  title, 
  enableInterpolation = true,
  markers = [],
  onMarkersChange 
}) => {
  const canvasRef = useRef(null);
  const overlayCanvasRef = useRef(null);
  const containerRef = useRef(null);
  const imageRef = useRef(null);
  
  const [viewport, setViewport] = useState({
    scale: 1,
    translation: { x: 0, y: 0 },
    windowWidth: 256,
    windowCenter: 128
  });
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const [lastMousePos, setLastMousePos] = useState({ x: 0, y: 0 });
  const [imageLoaded, setImageLoaded] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
  
  // 标记相关状态
  const [isMarkingMode, setIsMarkingMode] = useState(false);
  const [currentMarker, setCurrentMarker] = useState(null);
  const [isCreatingRegion, setIsCreatingRegion] = useState(false);
  const [regionStart, setRegionStart] = useState(null);
  const [contourPath, setContourPath] = useState([]); // 存储正在绘制的轮廓路径
  const [isDrawingContour, setIsDrawingContour] = useState(false); // 是否正在绘制轮廓
  const [showInstructions, setShowInstructions] = useState(false); // 控制操作说明的显示

  // 灰度值拾取相关状态
  const [pixelInfo, setPixelInfo] = useState(null); // 存储当前像素信息
  const [showPixelInfo, setShowPixelInfo] = useState(false); // 控制像素信息显示

  // 颜色列表用于新标记
  const markerColors = [
    '#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', 
    '#ffeaa7', '#dda0dd', '#98d8c8', '#f7dc6f'
  ];

  // 获取容器尺寸 - 优化版本
  const updateContainerSize = () => {
    if (containerRef.current) {
      const rect = containerRef.current.getBoundingClientRect();
      const newWidth = Math.floor(rect.width);
      const newHeight = Math.floor(rect.height);
      
      // 只在尺寸确实变化时才更新状态
      setContainerSize(prev => {
        if (prev.width !== newWidth || prev.height !== newHeight) {
          return { width: newWidth, height: newHeight };
        }
        return prev;
      });
    }
  };

  useEffect(() => {
    // 初始化时延迟一点执行，确保布局稳定
    const initTimer = setTimeout(() => {
      updateContainerSize();
    }, 100);
    
    const handleResize = () => {
      // 防抖处理resize事件
      clearTimeout(handleResize.timer);
      handleResize.timer = setTimeout(updateContainerSize, 150);
    };
    
    window.addEventListener('resize', handleResize);
    return () => {
      clearTimeout(initTimer);
      clearTimeout(handleResize.timer);
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  useEffect(() => {
    if (imageRef.current && imageLoaded && containerSize.width > 0 && containerSize.height > 0) {
      // 只在容器尺寸变化时重新绘制图像
      drawImage();
      drawMarkers();
    }
  }, [containerSize, imageLoaded, viewport, enableInterpolation]);

  // 单独处理标记变化，只重绘标记层
  useEffect(() => {
    if (imageRef.current && imageLoaded && containerSize.width > 0 && containerSize.height > 0) {
      drawMarkers();
    }
  }, [markers]);

  useEffect(() => {
    if (imageRef.current && imageLoaded && containerSize.width > 0 && containerSize.height > 0) {
      if (viewport.scale === 1) {
        const initialScale = calculateFitScale(imageRef.current);
        if (initialScale !== 1) {
          updateViewportSafely({
            scale: initialScale,
            translation: { x: 0, y: 0 },
            ...(type === 'processed' && {
              windowWidth: 255,
              windowCenter: 127.5
            })
          });
        }
      }
    }
  }, [imageLoaded, containerSize, type]);

  useEffect(() => {
    if (data) {
      loadImageData();
    }
  }, [data, currentImageIndex]);

  // 优化的重绘逻辑 - 使用防抖
  useEffect(() => {
    const timeoutId = setTimeout(() => {
      if (imageRef.current && imageLoaded) {
        // 只在viewport变化时重绘，标记变化已单独处理
        drawImage();
        drawMarkers();
      }
    }, 16);
    return () => clearTimeout(timeoutId);
  }, [viewport, imageLoaded, enableInterpolation]);

  // 点击外部关闭操作说明弹出框
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (showInstructions && !event.target.closest('.instructions-popup') && !event.target.closest('.help-btn')) {
        setShowInstructions(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [showInstructions]);

  // 添加键盘快捷键支持
  useEffect(() => {
    const handleKeyDown = (event) => {
      // 防止在输入框中触发快捷键
      if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
        return;
      }

      switch (event.key) {
        case 'ArrowLeft':
          event.preventDefault();
          if (currentImageIndex > 0) {
            setCurrentImageIndex(currentImageIndex - 1);
          }
          break;
        case 'ArrowRight':
          event.preventDefault();
          if (data && currentImageIndex < data.images.length - 1) {
            setCurrentImageIndex(currentImageIndex + 1);
          }
          break;
        case 'Home':
          event.preventDefault();
          setCurrentImageIndex(0);
          break;
        case 'End':
          event.preventDefault();
          if (data && data.images) {
            setCurrentImageIndex(data.images.length - 1);
          }
          break;
        case 'm':
        case 'M':
          event.preventDefault();
          toggleMarkingMode();
          break;
        case 'c':
        case 'C':
          if (isMarkingMode && markers.length > 0) {
            event.preventDefault();
            clearAllMarkers();
          }
          break;
        case 'r':
        case 'R':
          event.preventDefault();
          resetViewport();
          break;
        case 'Escape':
          event.preventDefault();
          if (isCreatingRegion) {
            setIsCreatingRegion(false);
            setRegionStart(null);
            setCurrentMarker(null);
          } else if (isDrawingContour) {
            setIsDrawingContour(false);
            setContourPath([]);
          } else if (isMarkingMode) {
            setIsMarkingMode(false);
          }
          break;
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [currentImageIndex, data, isMarkingMode, markers.length, isCreatingRegion]);

  // 计算适应容器的缩放比例
  const calculateFitScale = (img) => {
    if (!img || containerSize.width === 0 || containerSize.height === 0) {
      return 1;
    }
    
    const imageAspect = img.width / img.height;
    const containerAspect = containerSize.width / containerSize.height;
    
    let scale;
    if (imageAspect > containerAspect) {
      scale = (containerSize.width * 0.95) / img.width;
    } else {
      scale = (containerSize.height * 0.95) / img.height;
    }
    
    return Math.max(0.1, Math.min(10, scale));
  };

  const updateViewportSafely = (updates) => {
    setViewport(prev => ({
      ...prev,
      ...updates
    }));
  };

  // 加载图像数据 - 简化版本，主要支持DICOM
  const loadImageData = async () => {
    setImageLoaded(false);
    setErrorMessage('');

    try {
      if (type === 'dicom' && data.images && data.images.length > 0) {
        const imageData = data.images[currentImageIndex];
        
        if (imageData && imageData.imageId) {
          const img = new Image();
          img.crossOrigin = 'anonymous';
          
          img.onload = () => {
            imageRef.current = img;
            setImageLoaded(true);
          };
          
          img.onerror = (error) => {
            console.error('Image load failed:', error);
            setErrorMessage('图像加载失败');
          };
          
          img.src = imageData.imageId;
        } else {
          setErrorMessage('无效的图像数据');
        }
      }
    } catch (error) {
      console.error('加载图像失败:', error);
      setErrorMessage('加载失败: ' + error.message);
    }
  };

  // 绘制图像
  const drawImage = () => {
    const canvas = canvasRef.current;
    if (!canvas || !imageRef.current || !imageLoaded) return;

    const ctx = canvas.getContext('2d');
    
    // 只在尺寸确实变化时才设置canvas尺寸
    const targetWidth = containerSize.width;
    const targetHeight = containerSize.height;
    
    if (canvas.width !== targetWidth || canvas.height !== targetHeight) {
      canvas.width = targetWidth;
      canvas.height = targetHeight;
    }
    
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    const img = imageRef.current;
    const { scale, translation } = viewport;

    const drawWidth = img.width * scale;
    const drawHeight = img.height * scale;
    const drawX = (canvas.width - drawWidth) / 2 + translation.x;
    const drawY = (canvas.height - drawHeight) / 2 + translation.y;

    // 设置图像平滑
    ctx.imageSmoothingEnabled = enableInterpolation;
    if (enableInterpolation) {
      ctx.imageSmoothingQuality = 'high';
    }

    ctx.drawImage(img, drawX, drawY, drawWidth, drawHeight);
  };

  // 绘制标记
  const drawMarkers = () => {
    const canvas = overlayCanvasRef.current;
    if (!canvas || !imageRef.current || !imageLoaded) return;

    const ctx = canvas.getContext('2d');
    
    // 只在尺寸确实变化时才设置canvas尺寸
    const targetWidth = containerSize.width;
    const targetHeight = containerSize.height;
    
    if (canvas.width !== targetWidth || canvas.height !== targetHeight) {
      canvas.width = targetWidth;
      canvas.height = targetHeight;
    }
    
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    const img = imageRef.current;
    const { scale, translation } = viewport;

    const drawWidth = img.width * scale;
    const drawHeight = img.height * scale;
    const drawX = (canvas.width - drawWidth) / 2 + translation.x;
    const drawY = (canvas.height - drawHeight) / 2 + translation.y;

    // 绘制现有标记（只显示可见的标记）
    markers.filter(marker => marker.visible !== false).forEach(marker => {
      ctx.strokeStyle = marker.color;
      ctx.fillStyle = marker.color;
      ctx.lineWidth = 2;

      if (marker.type === 'point') {
        const x = drawX + (marker.x / img.width) * drawWidth;
        const y = drawY + (marker.y / img.height) * drawHeight;

        // 绘制十字标记
        ctx.beginPath();
        ctx.moveTo(x - 8, y);
        ctx.lineTo(x + 8, y);
        ctx.moveTo(x, y - 8);
        ctx.lineTo(x, y + 8);
        ctx.stroke();

        // 绘制中心点
        ctx.beginPath();
        ctx.arc(x, y, 3, 0, 2 * Math.PI);
        ctx.fill();

        // 绘制标签
        const textMetrics = ctx.measureText(marker.name);
        const textWidth = textMetrics.width + 8;
        ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
        ctx.fillRect(x + 10, y - 12, textWidth, 16);
        ctx.fillStyle = marker.color;
        ctx.font = '12px -apple-system, BlinkMacSystemFont, sans-serif';
        ctx.fillText(marker.name, x + 14, y - 2);

      } else if (marker.type === 'region') {
        const region = marker.region;
        const x = drawX + (region.x / img.width) * drawWidth;
        const y = drawY + (region.y / img.height) * drawHeight;
        const width = (region.width / img.width) * drawWidth;
        const height = (region.height / img.height) * drawHeight;

        // 绘制矩形框
        ctx.strokeRect(x, y, width, height);
        
        // 绘制半透明填充
        ctx.fillStyle = marker.color + '20';
        ctx.fillRect(x, y, width, height);

        // 绘制标签
        const textMetrics = ctx.measureText(marker.name);
        const textWidth = textMetrics.width + 8;
        ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
        ctx.fillRect(x, y - 20, textWidth, 16);
        ctx.fillStyle = marker.color;
        ctx.font = '12px -apple-system, BlinkMacSystemFont, sans-serif';
        ctx.fillText(marker.name, x + 4, y - 6);

      } else if (marker.type === 'contour') {
        const contour = marker.contour;
        if (contour.path && contour.path.length > 2) {
          // 绘制轮廓路径
          ctx.beginPath();
          const firstPoint = contour.path[0];
          const firstX = drawX + (firstPoint.x / img.width) * drawWidth;
          const firstY = drawY + (firstPoint.y / img.height) * drawHeight;
          ctx.moveTo(firstX, firstY);

          for (let i = 1; i < contour.path.length; i++) {
            const point = contour.path[i];
            const x = drawX + (point.x / img.width) * drawWidth;
            const y = drawY + (point.y / img.height) * drawHeight;
            ctx.lineTo(x, y);
          }
          ctx.closePath();
          
          // 绘制轮廓边框
          ctx.strokeStyle = marker.color;
          ctx.lineWidth = 2;
          ctx.stroke();
          
          // 绘制半透明填充
          ctx.fillStyle = marker.color + '20';
          ctx.fill();

          // 绘制标签（在轮廓的左上角）
          const bounds = contour.bounds;
          const labelX = drawX + (bounds.minX / img.width) * drawWidth;
          const labelY = drawY + (bounds.minY / img.height) * drawHeight;
          
          const textMetrics = ctx.measureText(marker.name);
          const textWidth = textMetrics.width + 8;
          ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
          ctx.fillRect(labelX, labelY - 20, textWidth, 16);
          ctx.fillStyle = marker.color;
          ctx.font = '12px -apple-system, BlinkMacSystemFont, sans-serif';
          ctx.fillText(marker.name, labelX + 4, labelY - 6);
        }
      }
    });

    // 绘制正在创建的区域
    if (isCreatingRegion && regionStart && currentMarker) {
      const currentX = currentMarker.canvasX;
      const currentY = currentMarker.canvasY;

      // 将canvas坐标转换为图像坐标，然后再转换为屏幕坐标进行绘制
      // 这确保预览矩形与最终矩形使用相同的坐标系统
      const startImageCoords = screenToImageCoords(regionStart.x, regionStart.y);
      const currentImageCoords = screenToImageCoords(currentX, currentY);
      
      if (startImageCoords && currentImageCoords && img) {
        const minX = Math.min(startImageCoords.x, currentImageCoords.x);
        const maxX = Math.max(startImageCoords.x, currentImageCoords.x);
        const minY = Math.min(startImageCoords.y, currentImageCoords.y);
        const maxY = Math.max(startImageCoords.y, currentImageCoords.y);
        
        // 转换回屏幕坐标进行绘制（与最终矩形标记相同的逻辑）
        const x = drawX + (minX / img.width) * drawWidth;
        const y = drawY + (minY / img.height) * drawHeight;
        const width = ((maxX - minX) / img.width) * drawWidth;
        const height = ((maxY - minY) / img.height) * drawHeight;

      ctx.strokeStyle = markerColors[markers.length % markerColors.length];
      ctx.lineWidth = 2;
      ctx.setLineDash([5, 5]);
        ctx.strokeRect(x, y, width, height);
        ctx.setLineDash([]);
      }
    }

    // 绘制正在创建的轮廓
    if (isDrawingContour && contourPath.length > 1) {
      ctx.strokeStyle = markerColors[markers.length % markerColors.length];
      ctx.lineWidth = 2;
      ctx.setLineDash([3, 3]);
      
      ctx.beginPath();
      const firstPoint = contourPath[0];
      const firstX = drawX + (firstPoint.x / img.width) * drawWidth;
      const firstY = drawY + (firstPoint.y / img.height) * drawHeight;
      ctx.moveTo(firstX, firstY);

      for (let i = 1; i < contourPath.length; i++) {
        const point = contourPath[i];
        const x = drawX + (point.x / img.width) * drawWidth;
        const y = drawY + (point.y / img.height) * drawHeight;
        ctx.lineTo(x, y);
      }
      
      // 绘制轮廓预览（不闭合）
      ctx.stroke();
      ctx.setLineDash([]);

      // 绘制路径点
      ctx.fillStyle = markerColors[markers.length % markerColors.length];
      contourPath.forEach((point, index) => {
        const x = drawX + (point.x / img.width) * drawWidth;
        const y = drawY + (point.y / img.height) * drawHeight;
        
        ctx.beginPath();
        ctx.arc(x, y, index === 0 ? 4 : 2, 0, 2 * Math.PI); // 起点稍大
        ctx.fill();
      });
    }
  };

  // 屏幕坐标转换为图像坐标
  const screenToImageCoords = (screenX, screenY) => {
    if (!imageRef.current) return { x: 0, y: 0 };

    const img = imageRef.current;
    const { scale, translation } = viewport;

    // 图像在canvas中的绘制位置和尺寸
    const drawWidth = img.width * scale;
    const drawHeight = img.height * scale;
    const drawX = (containerSize.width - drawWidth) / 2 + translation.x;
    const drawY = (containerSize.height - drawHeight) / 2 + translation.y;

    // 检查点击是否在图像区域内
    if (screenX < drawX || screenX > drawX + drawWidth || 
        screenY < drawY || screenY > drawY + drawHeight) {
      return null; // 点击在图像外
    }

    // 转换为图像坐标
    const imageX = ((screenX - drawX) / drawWidth) * img.width;
    const imageY = ((screenY - drawY) / drawHeight) * img.height;

    return {
      x: Math.max(0, Math.min(img.width - 1, Math.round(imageX))),
      y: Math.max(0, Math.min(img.height - 1, Math.round(imageY)))
    };
  };

  // 生成唯一ID
  const generateMarkerId = () => {
    return 'marker_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  };

  // 添加点标记
  const addPointMarker = (imageX, imageY) => {
    const newMarker = {
      id: generateMarkerId(),
      name: `点 ${markers.length + 1}`,
      type: 'point',
      x: imageX,
      y: imageY,
      color: markerColors[markers.length % markerColors.length],
      visible: true  // 标记是否可见（图像和TDC联动）
    };

    const updatedMarkers = [...markers, newMarker];
    onMarkersChange(updatedMarkers);
  };

  // 添加区域标记（矩形）
  const addRegionMarker = (startX, startY, endX, endY) => {
    const x = Math.min(startX, endX);
    const y = Math.min(startY, endY);
    const width = Math.abs(endX - startX);
    const height = Math.abs(endY - startY);

    if (width < 5 || height < 5) return; // 太小的区域不创建

    const newMarker = {
      id: generateMarkerId(),
      name: `区域 ${markers.filter(m => m.type === 'region' || m.type === 'contour').length + 1}`,
      type: 'region',
      region: { x, y, width, height },
      color: markerColors[markers.length % markerColors.length],
      visible: true  // 标记是否可见（图像和TDC联动）
    };

    const updatedMarkers = [...markers, newMarker];
    onMarkersChange(updatedMarkers);
  };

  // 添加轮廓标记
  const addContourMarker = (path) => {
    if (path.length < 3) return; // 至少需要3个点才能形成轮廓

    // 计算轮廓的边界框
    const xs = path.map(p => p.x);
    const ys = path.map(p => p.y);
    const minX = Math.min(...xs);
    const maxX = Math.max(...xs);
    const minY = Math.min(...ys);
    const maxY = Math.max(...ys);

    // 检查轮廓是否太小
    if (maxX - minX < 10 || maxY - minY < 10) return;

    const newMarker = {
      id: generateMarkerId(),
      name: `轮廓 ${markers.filter(m => m.type === 'contour' || m.type === 'region').length + 1}`,
      type: 'contour',
      contour: {
        path: path,
        bounds: { minX, maxX, minY, maxY }
      },
      color: markerColors[markers.length % markerColors.length],
      visible: true  // 标记是否可见（图像和TDC联动）
    };

    const updatedMarkers = [...markers, newMarker];
    onMarkersChange(updatedMarkers);
  };

  // 删除标记
  const deleteMarker = (markerId) => {
    const updatedMarkers = markers.filter(m => m.id !== markerId);
    onMarkersChange(updatedMarkers);
  };

  // 使用射线法判断点是否在轮廓内部
  const isPointInContour = (point, contourPath) => {
    if (contourPath.length < 3) return false;
    
    let isInside = false;
    const { x, y } = point;
    
    for (let i = 0, j = contourPath.length - 1; i < contourPath.length; j = i++) {
      const xi = contourPath[i].x;
      const yi = contourPath[i].y;
      const xj = contourPath[j].x;
      const yj = contourPath[j].y;
      
      if (((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)) {
        isInside = !isInside;
      }
    }
    
    return isInside;
  };

  // 获取相对于canvas的鼠标坐标
  const getCanvasCoords = (event) => {
    const canvas = overlayCanvasRef.current;
    const rect = canvas.getBoundingClientRect();
    
    // 考虑canvas的缩放和偏移
    const scaleX = canvas.width / rect.width;
    const scaleY = canvas.height / rect.height;
    
    return {
      x: (event.clientX - rect.left) * scaleX,
      y: (event.clientY - rect.top) * scaleY
    };
  };

  // 获取指定坐标的像素值 - 使用useCallback优化
  const getPixelValueAt = useCallback((canvasX, canvasY) => {
    const canvas = canvasRef.current;
    const img = imageRef.current;
    if (!canvas || !img || !imageLoaded) return null;

    try {
      // 将画布坐标转换为图像坐标
      const centerX = canvas.width / 2;
      const centerY = canvas.height / 2;
      
      const imageX = Math.round((canvasX - centerX) / viewport.scale - viewport.translation.x + img.width / 2);
      const imageY = Math.round((canvasY - centerY) / viewport.scale - viewport.translation.y + img.height / 2);
      
      // 检查坐标是否在图像范围内
      if (imageX < 0 || imageX >= img.width || imageY < 0 || imageY >= img.height) {
        return null;
      }

      // 对于处理后的图像，获取真实参数值
      // 注意：TDCImageViewer主要用于原始DICOM图像，所以这里主要处理DICOM数据
      // 从canvas获取像素数据
      const ctx = canvas.getContext('2d');
      const imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
      const pixelData = imageData.data;
      
      // 计算灰度值 (如果是RGB则转换为灰度)
      const grayValue = Math.round(0.299 * pixelData[0] + 0.587 * pixelData[1] + 0.114 * pixelData[2]);
      
      return {
        x: imageX,
        y: imageY,
        grayValue: grayValue,
        rgbValue: `R:${pixelData[0]} G:${pixelData[1]} B:${pixelData[2]}`,
        canvasX: Math.round(canvasX),
        canvasY: Math.round(canvasY),
        isParameterImage: false
      };
    } catch (error) {
      console.warn('获取像素值失败:', error);
      return null;
    }
  }, [imageLoaded, viewport.scale, viewport.translation]);

  // 鼠标事件处理
  const handleMouseDown = (event) => {
    const canvasCoords = getCanvasCoords(event);
    const x = canvasCoords.x;
    const y = canvasCoords.y;

    if (isMarkingMode) {
      // 只有左键点击才添加标记，右键用于删除
      if (event.button === 0) { // 0 = 左键
      if (event.ctrlKey || event.metaKey) {
          // 按住Ctrl/Cmd开始创建矩形区域
        setIsCreatingRegion(true);
        setRegionStart({ x, y });
          setCurrentMarker({ canvasX: x, canvasY: y });
        } else if (event.shiftKey) {
          // 按住Shift开始绘制自由轮廓
          const imageCoords = screenToImageCoords(x, y);
          if (imageCoords) {
            setIsDrawingContour(true);
            setContourPath([imageCoords]);
          }
        } else if (event.altKey) {
          // 按住Alt键+左键点击创建点标记
        const imageCoords = screenToImageCoords(x, y);
        if (imageCoords) { // 确保点击在图像内
          addPointMarker(imageCoords.x, imageCoords.y);
        }
        } else {
          // 普通左键拖拽 - 即使在标记模式下也可以拖拽图片
          setIsDragging(true);
          setLastMousePos({ x: event.clientX, y: event.clientY });
        }
      }
      // 右键点击不在这里处理，交给 handleContextMenu 处理
    } else {
      // 普通的平移拖拽（只响应左键）
      if (event.button === 0) {
      setIsDragging(true);
      setLastMousePos({ x: event.clientX, y: event.clientY });
      }
    }
  };

  const handleMouseMove = (event) => {
    if (isCreatingRegion) {
      const canvasCoords = getCanvasCoords(event);
      setCurrentMarker({ canvasX: canvasCoords.x, canvasY: canvasCoords.y });
      // 重绘标记层显示预览
      requestAnimationFrame(() => drawMarkers());
    } else if (isDrawingContour) {
      // 正在绘制轮廓时，添加路径点
      const canvasCoords = getCanvasCoords(event);
      const imageCoords = screenToImageCoords(canvasCoords.x, canvasCoords.y);
      if (imageCoords) {
        setContourPath(prev => {
          const lastPoint = prev[prev.length - 1];
          // 只有当鼠标移动足够距离时才添加新点，避免点过于密集
          const distance = Math.sqrt(
            Math.pow(imageCoords.x - lastPoint.x, 2) + 
            Math.pow(imageCoords.y - lastPoint.y, 2)
          );
          if (distance > 3) {
            return [...prev, imageCoords];
          }
          return prev;
        });
        // 重绘标记层显示轮廓预览
        requestAnimationFrame(() => drawMarkers());
      }
    } else if (isDragging) {
      const deltaX = event.clientX - lastMousePos.x;
      const deltaY = event.clientY - lastMousePos.y;

      updateViewportSafely({
        translation: {
          x: viewport.translation.x + deltaX,
          y: viewport.translation.y + deltaY
        }
      });

      setLastMousePos({ x: event.clientX, y: event.clientY });
    } else if (currentTool === 'pick' && imageLoaded && !isMarkingMode) {
      // 灰度值拾取模式 - 鼠标悬停时获取像素信息
      const canvasCoords = getCanvasCoords(event);
      const pixelData = getPixelValueAt(canvasCoords.x, canvasCoords.y);
      setPixelInfo(pixelData);
      setShowPixelInfo(pixelData !== null);
    }
  };

  const handleMouseUp = (event) => {
    // 只处理左键释放事件
    if (event.button === 0) {
    if (isCreatingRegion && regionStart) {
      const canvasCoords = getCanvasCoords(event);
      const endX = canvasCoords.x;
      const endY = canvasCoords.y;

      const startImageCoords = screenToImageCoords(regionStart.x, regionStart.y);
      const endImageCoords = screenToImageCoords(endX, endY);

      if (startImageCoords && endImageCoords) { // 确保两个点都在图像内
        addRegionMarker(
          startImageCoords.x, startImageCoords.y,
          endImageCoords.x, endImageCoords.y
        );
      }

      setIsCreatingRegion(false);
      setRegionStart(null);
      setCurrentMarker(null);
      } else if (isDrawingContour && contourPath.length > 0) {
        // 完成轮廓绘制
        addContourMarker(contourPath);
        setIsDrawingContour(false);
        setContourPath([]);
    }
    
    setIsDragging(false);
    }
  };

  // 右键菜单 - 删除标记
  const handleContextMenu = (event) => {
    event.preventDefault();
    
    if (!isMarkingMode) return;

    const canvasCoords = getCanvasCoords(event);
    const imageCoords = screenToImageCoords(canvasCoords.x, canvasCoords.y);
    
    if (!imageCoords) return; // 点击在图像外

    // 查找点击位置的标记
    const clickedMarker = markers.find(marker => {
      if (marker.type === 'point') {
        const distance = Math.sqrt(
          Math.pow(marker.x - imageCoords.x, 2) + Math.pow(marker.y - imageCoords.y, 2)
        );
        return distance < 15; // 15像素容差
      } else if (marker.type === 'region') {
        const region = marker.region;
        return imageCoords.x >= region.x && 
               imageCoords.x <= region.x + region.width &&
               imageCoords.y >= region.y && 
               imageCoords.y <= region.y + region.height;
      } else if (marker.type === 'contour') {
        // 使用射线法判断点是否在轮廓内部
        return isPointInContour(imageCoords, marker.contour.path);
      }
      return false;
    });

    if (clickedMarker) {
      if (window.confirm(`确定要删除标记"${clickedMarker.name}"吗？`)) {
        deleteMarker(clickedMarker.id);
      }
    }
  };

  // 鼠标滚轮缩放
  const handleWheel = (event) => {
    event.preventDefault();
    
    const delta = -event.deltaY;
    const scaleFactor = delta > 0 ? 1.1 : 0.9;
    const newScale = Math.max(0.1, Math.min(10, viewport.scale * scaleFactor));
    
    updateViewportSafely({ scale: newScale });
  };

  // 重置视图
  const resetViewport = () => {
    if (imageRef.current) {
      const fitScale = calculateFitScale(imageRef.current);
      updateViewportSafely({
        scale: fitScale,
        translation: { x: 0, y: 0 }
      });
    }
  };

  // 获取光标样式
  const getCursorStyle = () => {
    if (isDragging) {
      return 'grabbing';
    }
    
    if (isMarkingMode) {
      if (isCreatingRegion) return 'crosshair';
      if (isDrawingContour) return 'copy';
      return 'grab'; // 标记模式下默认也可以拖拽
    }
    
    if (currentTool === 'pick') {
      return 'crosshair';
    }
    
    return 'grab';
  };

  // 切换标记模式
  const toggleMarkingMode = () => {
    setIsMarkingMode(!isMarkingMode);
    setIsCreatingRegion(false);
    setRegionStart(null);
    setCurrentMarker(null);
    setIsDrawingContour(false);
    setContourPath([]);
    setShowInstructions(false); // 关闭操作说明弹出框
  };

  // 清除所有标记
  const clearAllMarkers = () => {
    if (markers.length > 0 && window.confirm('确定要清除所有标记吗？')) {
      onMarkersChange([]);
    }
  };

  if (errorMessage) {
    return (
      <div className="image-viewer-error">
        <div className="error-content">
          <div className="error-icon">⚠️</div>
          <div className="error-message">{errorMessage}</div>
          <button onClick={() => loadImageData()} className="retry-btn">
            重试
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="image-viewer" ref={containerRef}>
      {/* 工具栏 */}
      <div className="tdc-toolbar">
        <div className="toolbar-group">
          <button
            className={`tool-btn ${isMarkingMode ? 'active' : ''}`}
            onClick={toggleMarkingMode}
            title={isMarkingMode ? '退出标记模式 (M)' : '进入标记模式 (M)'}
          >
            📍 {isMarkingMode ? '退出标记' : '开始标记'}
          </button>
          
          {isMarkingMode && (
            <>
              <span className="tool-separator">|</span>
              <button
                className="help-btn"
                onClick={() => setShowInstructions(!showInstructions)}
                title="查看操作说明"
              >
                ❓
              </button>
              {showInstructions && (
                <div className="instructions-popup">
                  <div className="instructions-content">
                    <div className="instructions-header">
                      <span>操作说明</span>
                      <button 
                        className="close-btn"
                        onClick={() => setShowInstructions(false)}
                      >
                        ×
                      </button>
                    </div>
                    <div className="instructions-list">
                      <div className="instruction-item">
                        <span className="key">Alt+左键点击</span>
                        <span className="action">添加点标记</span>
                      </div>
                      <div className="instruction-item">
                        <span className="key">Ctrl+左键拖拽</span>
                        <span className="action">添加矩形区域</span>
                      </div>
                      <div className="instruction-item">
                        <span className="key">Shift+左键拖拽</span>
                        <span className="action">绘制自由轮廓</span>
                      </div>
                      <div className="instruction-item">
                        <span className="key">左键拖拽</span>
                        <span className="action">拖拽移动图片</span>
                      </div>
                      <div className="instruction-item">
                        <span className="key">右键</span>
                        <span className="action">删除标记</span>
                      </div>
                      <div className="instruction-item">
                        <span className="key">ESC</span>
                        <span className="action">取消操作</span>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </>
          )}
        </div>

        <div className="toolbar-group">
          <button onClick={resetViewport} className="tool-btn" title="适应窗口 (R)">
            🔍 适应
          </button>
          
          {markers.length > 0 && (
            <button onClick={clearAllMarkers} className="tool-btn danger" title="清除所有标记 (C)">
              🗑️ 清除
            </button>
          )}
          
          <span className="marker-count-display">
            {markers.length} 个标记
          </span>
          
          {data && data.images && data.images.length > 1 && (
            <>
              <span className="tool-separator">|</span>
              <div className="frame-shortcuts">
                <span>← → 切换帧</span>
                <span>Home/End 首末帧</span>
              </div>
            </>
          )}
        </div>
      </div>

      {/* 图像显示区域 */}
      <div className="canvas-container" style={{ cursor: getCursorStyle() }}>
        <canvas
          ref={canvasRef}
          className="image-canvas"
          style={{ position: 'absolute', zIndex: 1 }}
        />
        <canvas
          ref={overlayCanvasRef}
          className="overlay-canvas"
          style={{ position: 'absolute', zIndex: 2 }}
          onMouseDown={handleMouseDown}
          onMouseMove={handleMouseMove}
          onMouseUp={handleMouseUp}
          onMouseLeave={() => {
            // 当鼠标离开时隐藏像素信息
            if (currentTool === 'pick') {
              setShowPixelInfo(false);
              setPixelInfo(null);
            }
          }}
          onContextMenu={handleContextMenu}
          onWheel={handleWheel}
        />
      </div>

      {/* 使用和原始视图相同的slider控件 */}
      {data && data.images && data.images.length > 1 && (
        <div className="frame-slider-bottom">
          <div className="slider-container">
            <div className="slider-track">
              <input
                type="range"
                min="0"
                max={data.images.length - 1}
                value={currentImageIndex}
                onChange={(e) => setCurrentImageIndex(parseInt(e.target.value))}
                className="frame-slider-main"
              />
              <div className="slider-progress" 
                   style={{ width: `${(currentImageIndex / (data.images.length - 1)) * 100}%` }}
              />
            </div>
            <span className="frame-counter">
              {currentImageIndex + 1} / {data.images.length}
            </span>
          </div>
        </div>
      )}

      {/* 添加视图信息栏，显示标记状态 */}
      <div className="viewer-info">
        <div className="viewport-info">
          <span>缩放: {viewport.scale.toFixed(2)}x</span>
          <span>标记模式: {isMarkingMode ? '开启' : '关闭'}</span>
          <span>标记数量: {markers.length}</span>
          {isMarkingMode && (
            <span>操作: {
              isCreatingRegion ? '创建矩形区域' : 
              isDrawingContour ? '绘制自由轮廓' : 
              'Alt+点击添加点，可拖拽图片'
            }</span>
          )}
          {/* 像素信息显示 */}
          {showPixelInfo && pixelInfo && (
            <span className="pixel-info">
              坐标: ({pixelInfo.x}, {pixelInfo.y}) | 灰度: {pixelInfo.grayValue}
            </span>
          )}
        </div>
        <div className="image-info">
          <span>当前工具: {currentTool === 'pick' ? '灰度拾取' : '标记TDC'}</span>
          <span>帧: {currentImageIndex + 1}/{data?.images?.length || 0}</span>
          <span>状态: {imageLoaded ? '已加载' : '加载中'}</span>
          <span>类型: TDC分析</span>
          {/* 显示文件名信息 */}
          {data && (
            <>
              {data.metadata?.fileCount > 1 ? (
                // 多文件场景：显示当前帧的文件名
                data.images && data.images[currentImageIndex] && (
                  <span>文件: {data.images[currentImageIndex].fileName || '未知'}</span>
                )
              ) : (
                // 单文件（多帧）场景：显示源文件名
                data.metadata?.originalFileName && (
                  <span>文件: {data.metadata.originalFileName}</span>
                )
              )}
              {data.metadata?.fileCount && (
                <span>总文件: {data.metadata.fileCount}个</span>
              )}
            </>
          )}
          <span>容器: {containerSize.width}×{containerSize.height}</span>
          {/* 在拾取模式下显示操作提示 */}
          {currentTool === 'pick' && !isMarkingMode && (
            <span className="pick-tip">💡 移动鼠标查看像素值</span>
          )}
        </div>
      </div>
    </div>
  );
};

export default TDCImageViewer;